import { type MaySuccess } from '@gnlab/utils'
import { API } from '@/services/common/api'
import type { RawBaseContact } from '@/services/contacts'
import { ContactType, formatRawBaseContact } from '@/services/contacts'
import { type InternalContact } from './index'

/**
 * 获取员工列表
 */
interface RawInternalContact extends RawBaseContact {
  wx_id: string
}
export function formatRawInternalContact(raw: RawInternalContact): InternalContact {
  return {
    ...formatRawBaseContact(raw.wx_id, raw),
    type: ContactType.internal,
    sex: raw.sex,
  }
}
async function getInternals(params: {
  wxids: string[]
  page: number
  pageSize: number
  format?: true
}): Promise<MaySuccess<InternalContact[]>>
async function getInternals(params: {
  wxids: string[]
  page: number
  pageSize: number
  format: false
}): Promise<MaySuccess<RawInternalContact[]>>
async function getInternals({
  wxids,
  page,
  pageSize,
  format = true,
}: {
  wxids: string[]
  page: number
  pageSize: number
  format?: boolean
}) {
  return API<RawInternalContact[] | InternalContact[]>('/Contact/InnerContactList', {
    data: {
      wxids,
      pageIndex: page,
      pageSize,
    },
    ...(format
      ? { formatter: (raw: RawInternalContact[]) => raw.map(formatRawInternalContact) }
      : {}),
  })
}
export { getInternals }

/**
 * 根据关键词搜索员工
 */
export async function searchInternals(wxids: string[], keyword: string, page = 1, pageSize = 100) {
  return API('/Contact/InnerContactsByKeyword', {
    data: {
      wxids,
      keyword,
      PageIndex: page,
      PageSize: pageSize,
    },
    formatter: (raw: RawInternalContact[]) => raw.map(formatRawInternalContact),
  })
}
